﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using TextBox = System.Windows.Forms.TextBox;
using Button = System.Windows.Forms.Button;

namespace sy1_10
{
    public partial class Form1 : Form
    {
        private readonly Regex numberRegex = new Regex(@"^\d*\.?\d+$");
        private bool operand1Valid = false;
        private bool operand2Valid = false;
        private bool isClearing = false; 

        public Form1()
        {
            InitializeComponent();
            UpdateOperationButtons();
        }

        private void TextBox1_Leave(object sender, EventArgs e)
        {
            if (!isClearing) 
            {
                ValidateOperand(TextBox1, ref operand1Valid);
            }
        }

        private void TextBox2_Leave(object sender, EventArgs e)
        {
            if (!isClearing) 
            {
                ValidateOperand(TextBox2, ref operand2Valid);
            }
        }

        private void ValidateOperand(TextBox textBox, ref bool validFlag)
        {
            if (string.IsNullOrEmpty(textBox.Text))
            {
                validFlag = false;
                if (!isClearing)
                {
                    MessageBox.Show("操作数不得为空！", "输入错误",
                                   MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textBox.Focus();
                }
            }
            else if (!numberRegex.IsMatch(textBox.Text))
            {
                validFlag = false;
                MessageBox.Show("只能是整数(>=0)，请重试!", "输入错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBox.SelectAll();
                textBox.Focus();
            }
            else
            {
                validFlag = true;
            }

            UpdateOperationButtons();
        }

        private void UpdateOperationButtons()
        {
            bool enableButtons = operand1Valid && operand2Valid;

            ButtonAdd.Enabled = enableButtons;
            ButtonSubtract.Enabled = enableButtons;
            ButtonMultiply.Enabled = enableButtons;
            ButtonDivide.Enabled = enableButtons;
        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            Calculate((a, b) => a + b, "加法");
        }

        private void ButtonSubtract_Click(object sender, EventArgs e)
        {
            Calculate((a, b) => a - b, "减法");
        }

        private void ButtonMultiply_Click(object sender, EventArgs e)
        {
            Calculate((a, b) => a * b, "乘法");
        }

        private void ButtonDivide_Click(object sender, EventArgs e)
        {
            try
            {
                double num1 = double.Parse(TextBox1.Text);
                double num2 = double.Parse(TextBox2.Text);

                if (num2 == 0)
                {
                    MessageBox.Show("除数不得为零！", "除零错误",
                                   MessageBoxButtons.OK, MessageBoxIcon.Error);
                    TextBox2.SelectAll();
                    TextBox2.Focus();
                    return;
                }

                double result = num1 / num2;
                TextBox3.Text = FormatResult(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"除法运算错误：{ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Calculate(Func<double, double, double> operation, string operationName)
        {
            try
            {
                double num1 = double.Parse(TextBox1.Text);
                double num2 = double.Parse(TextBox2.Text);
                double result = operation(num1, num2);
                TextBox3.Text = FormatResult(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{operationName}运算错误：{ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string FormatResult(double result)
        {
            if (result == Math.Floor(result))
            {
                return ((int)result).ToString();
            }
            else
            {
                return result.ToString("0.####");
            }
        }

        private void ButtonClear_Click(object sender, EventArgs e)
        {
            isClearing = true; 

            TextBox1.Clear();
            TextBox2.Clear();
            TextBox3.Clear();
            operand1Valid = false;
            operand2Valid = false;
            UpdateOperationButtons();
            TextBox1.Focus();

            isClearing = false; 
        }

        private void ButtonExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出程序吗？", "退出确认",
                               MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            if (!isClearing) 
            {
                ValidateOperand(TextBox1, ref operand1Valid);
            }
        }

        private void TextBox2_TextChanged(object sender, EventArgs e)
        {
            if (!isClearing) 
            {
                ValidateOperand(TextBox2, ref operand2Valid);
            }
        }
    }
}